<!-- 页面表格配置与标题组件 -->
<template>
  <div class="flex_row_center ">
    <div style="height:32px;display: flex;align-items: center;line-height: 1;">{{ $t('label_current_position') }}：</div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item v-for="(item, index) in pathList" :key="index">
        <span class="bold">
          {{ $tt(item.name || item.module) }}
        </span>
      </el-breadcrumb-item>
    </el-breadcrumb>
    <el-button v-if="pageOption" class="mg_h2" icon="el-icon-s-tools" size="mini" circle @click="clickOption"></el-button>
    <el-dialog :title="$t('label_page_table_setting')" :visible.sync="visible" custom-class="dialog_mini">
      <ex_super_table :data="tableKeyList" v-bind="bindFilterTable" ref="tableKeyTable"
        @selection-change="e => selection = e">
      </ex_super_table>
      <div class="flex_row flex_justify_sb">
        <el-button type="primary" @click.stop="clickResetDefaultOption">{{ $tt('label_restore_default') }}</el-button>
        <span>
          <el-button @click.stop="visible = false">{{ $tt('label_cancel') }}</el-button>
          <el-button type="primary" @click.stop="_saveOption">{{ $tt('label_save_and_apply') }}</el-button>
        </span>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import index_privs from "@/router/_index_privs";
export default {
  name: 'page_breadcrumb',
  data() {
    return {
      selection: [],
      path: '',
      visible: false,
      pathList: [],
      bindFilterTable: {
        showIndex: false,
        autoFlex: false,
        height: 500,
        'row-class-name': this.rowClassMethod,
        'row-key': (row) => `${row.key}_${row.type}_${row._index}_${row._time}`,

        model: [
          {
            key: "keyShow", label: "label_display", width: 80,
            render: (h, { row, column }) => {
              const value = row[column.property]
              const disabled = !!row['keyShowForce']
              return (<el-checkbox value={value} disabled={disabled} onChange={e=>this.$set(row,column.property,e)}></el-checkbox>)
            },
          },
          {
            key: "keySort", label: 'label_sort_index', width: 180,
            render: (h, { row, column, index, list }) => {
              const move = row.type != 'operate'
              const ig = move ? 'sortable_control_handle' : 'sortable_control_ignore'

              return (<div class="flex_center">
                <div class={"mg_l1 "+ig} style={move ? "cursor: move;" : ""}>
                  <i class={move ? "el-icon-sort" : ""}></i>
                </div>
                <el-button type='text' disabled={(index <= 0)||this._disabledMove(index - 1)||this._disabledMove(index)} onClick={e => this._sortKeyChange(index, index - 1)}>
                  {this.$t('label_up_move')}
                </el-button>
                <el-button type='text' disabled={(index >= list.length - 1)||this._disabledMove(index + 1)||this._disabledMove(index)} onClick={e => this._sortKeyChange(index, index + 1)}>
                  {this.$t('label_down_move')}
                </el-button>
              </div>)
            }
          },
          { key: 'label', label: 'label_show_field', 'min-width': 160, 'show-overflow-tooltip': true, formatter: (r, c, v) => this.$tt(v) },
          // {
          //   label: 'label_operate', width: 120, slot: 'custom_operate'
          // }
        ]
      },
      currentDraggableItem: null,
      allKey: {},
      tableKeyList: [],
    }
  },
  props: {
    getKeyMethod: Function,
    pageOption: {
      type: Boolean,
      default: false,
    },
    modelPath: String,
  },
  inject: ['tagItemInject'],
  computed: {
    isHasExpandDesc() {
      return _.values(this.allKey).some(v => v.some(it => it.type == 'expandDesc'))
    },
  },
  created() {
    this.path = this.$route.path
    let pathList = this.findRoutePath(index_privs)
    if (pathList == false) {
      this.$nextTick(() => {
        if (this.tagItemInject) {
          this.pathList = [{ name: this.tagItemInject().label }]
        }
      })
    }
    this.pathList = pathList
  },
  mounted() {


  },
  methods: {
    clickResetDefaultOption() {
      this.$emit("change", null, this.path, this.modelPath)
      this.visible = false
    },
    clickOption() {

      this.visible = !this.visible
      if (this.visible) {


        this.tableKeyList = this.doWithKey(this.getKeyMethod({
          dataType: 'current',
          filterAttrs: true,
        }),)
        this.allKey = _.groupBy(
          this.tableKeyList,
          it => it.keyGroup || (it.type ? 'label_operate_function' : 'label_base_info'))
        this.tableKeyList.sort((a, b) => a.keySort - b.keySort)

        this._sortKeyReset()
        this.$nextTick(() => {
          if (this.$refs.tableKeyTable) {
            this.tableKeyList.forEach(row => {
              this.$refs.tableKeyTable.toggleRowSelection(row, !!row.keyShow)
            })
            this.$refs.tableKeyTable.setSortable({
              handle: ".sortable_control_handle",
              filter: ".sortable_control_ignore",  // 过滤器，不需要进行拖动的元素
              onStart: (evt) => {
                this.currentDraggableItem = this.tableKeyList[evt.oldIndex];
              },
              onEnd: async (evt) => {
                this._sortKeyChangeObj(this.currentDraggableItem, this.tableKeyList, evt.newIndex)
                this.currentDraggableItem = null
              }
            })
          }
        })
      }
    },


    doWithKey(keyList,) {
      return keyList.map((it, i) => {
        it._index = i
        it._time = new Date().getTime()
        if (it.type) {
          if (it.type == 'selection') {
            it.label = "label_table_select_area"
          } else if (it.type == 'operate') {
            it.label = "label_table_operate_area"
          } else if (it.type == 'expandDesc') {
            it.label = "label_detail_expand"
          }
        }
        return it
      })
    },
    doWithReturnKey(list) {
      return list.map((it, index) => {
        it.keySort = index
        // let { keyGroup, keyShowForce,render, label,_index,_time, ...out } = it
        return _.pick(it, ['key', 'label', 'type', 'fixed', 'keyShow', 'keySort'])
      })
    },
    rowClassMethod({ row, rowIndex }) {
      if (this.currentDraggableItem) {
        let c = this._displayButtonBind(this.currentDraggableItem).sort
        let r = this._displayButtonBind(row).sort
        if (c ^ r) {
          return 'back_info_light back_info_light_hover'
        }
      }

    },
    findRoutePath(list) {
      for (let i = 0; i < list.length; i++) {
        let item = list[i]
        if (item.children) {
          let result = this.findRoutePath(item.children)
          if (result) {
            return [item, ...result]
          }
        } else if (item.path == this.path) {
          return [item]
        }
      }
      return false
    },

    _disabledMove(item) {
      if (_.isNumber(item)) {
        item = this.tableKeyList[item]
      }
      return !item || item.type == 'operate'
    },
    _sortKeyChangeObj(oldObj, newList, newIndex) {
      let newObj = newIndex < newList.length ? newList[newIndex] : newList[newList.length - 1]
      this._sortKeyChange(oldObj, newObj)
    },
    _sortKeyChange(oldObj, newObj) {
      if (_.isNumber(oldObj)) {
        oldObj = this.tableKeyList[oldObj]
      }
      if (_.isNumber(newObj)) {
        newObj = this.tableKeyList[newObj]
      }
      if (this._disabledMove(oldObj) || this._disabledMove(newObj)) {

      } else {
        const _olaIndex = _.findIndex(this.tableKeyList, oldObj)
        const _newIndex = _.findIndex(this.tableKeyList, newObj)
        if (_olaIndex >= 0 && _newIndex >= 0 && _olaIndex != _newIndex) {
          this.tableKeyList.splice(_newIndex, 0, this.tableKeyList.splice(_olaIndex, 1)[0])
        }
      }
      this.$nextTick(() => {
        this.tableKeyList = this._sortKeyReset()
      })

    },
    _sortKeyReset() {
      return this.tableKeyList.map((it, i) => {
        it._index = i
        it._time = new Date().getTime()
        return it
      }).sort((a, b) => {
        let a_number = this._displayButtonBind(a).sort
        let b_number = this._displayButtonBind(b).sort
        return a_number - b_number
      })

    },

    _displayButtonBind(item) {
      if (item.type == 'operate') return { icon: 'el-icon-caret-right', type: 'primary', value: 'right', sort: 3 }
      if (item.keyShow == 'expandDesc') return { icon: 'el-icon-menu', type: 'primary', value: 'expandDesc', sort: 4 }
      if (item.fixed == 'right') return { icon: 'el-icon-caret-right', type: 'primary', value: 'right', sort: 2 }
      if (item.fixed == 'left' || item.fixed == true) return { icon: 'el-icon-caret-left', type: 'primary', value: 'left', sort: 0 }
      return { icon: 'el-icon-paperclip', type: 'default', value: 'default', sort: 1 }
    },

    _saveOption() {
      this.$emit("change", this.doWithReturnKey(this.tableKeyList), this.path, this.modelPath)
      this.visible = false
    },
  },
}
</script>

<style scoped>
.custom_operate_div {
  height: 30px;
  justify-content: end;
}

.el-table--enable-row-hover .el-table__body tr:hover .custom_operate_div>.item_hidden {
  display: block;
}

.item_hidden :hover {
  display: block;
}

.item_hidden {
  display: none;
}
</style>
